package org.yufan.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.yufan.common.Result;
import org.yufan.common.ResultUtils;
import org.yufan.utils.JsonUtils;
import org.yufan.utils.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class CustomerHandlerException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {

        String msg;
        if(exception instanceof CustomerException){
            //如果是自定义取出具体的异常信息
            msg=exception.getMessage();
        }else{
            //不可预期的异常
            msg="对不起，系统开小差了,请联系管理员!";
        }

        //如果返回的是json数据，应该响应json，而不是跳转到error页面

        ModelAndView modelAndView=new ModelAndView();
        HandlerMethod  handlerMethod= (HandlerMethod) handler;
        //得到controller当前执行的方法
        Method method=handlerMethod.getMethod();

        //判断controller的方法是是否有responseBody注解或者返回responseEntity
        ResponseBody responseBody = AnnotationUtils.findAnnotation(method, ResponseBody.class);

        if(responseBody!=null||ResponseEntity.class.getName().equals(method.getReturnType().getName())){
            //返回json数据
            Result result = ResultUtils.buildFail(100, msg);
            String json=JsonUtils.objectToJson(result);
            //返回结果给调用方
            ResponseUtils.responseJson(response,json);
            return   modelAndView;
        }

        modelAndView.setViewName("error/exception.jsp");
        modelAndView.addObject("msg",msg);
        return modelAndView;

    }


}
